#include <iostream>
#include <Windows.h>
#include <direct.h>
#include <fstream>
#include <TlHelp32.h>
#include <tchar.h>
#include "AES.h"
#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" ) //隐藏运行界面
using namespace std;

#define OUTPUT_DIR "C:\\ProgramData\\temp\\out"
#define PIN_FILE "config.ini"
#define PIN_LEN 16
#define ENCRYPT_LEN 128
#define PPT_PROC "POWERPNT.EXE"
#pragma warning(disable:4996) 

//判断进程是否存在
BOOL FindProcess()
{
	int i = 0;
	PROCESSENTRY32 pe32;
	pe32.dwSize = sizeof(pe32);
	HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hProcessSnap == INVALID_HANDLE_VALUE)
	{
		i += 0;
	}
	BOOL bMore = ::Process32First(hProcessSnap, &pe32);
	while (bMore)
	{
		//printf(" 进程名称：%s \n", pe32.szExeFile);
		if (stricmp("POWERPNT.EXE", pe32.szExeFile) == 0)
		{
			//printf("进程运行中");
			i += 1;
		}
		bMore = ::Process32Next(hProcessSnap, &pe32);
	}
	if (i>1) {           //大于1，排除自身
		return true;
	}
	else {
		return false;
	}
}


int main()
{
	//获取本文件夹下的PPS或者PPSX文件
	WIN32_FIND_DATA wfd;
	HANDLE handle;
	if (0!=(handle = FindFirstFile("*.pps", &wfd)))
	{
		string str_ppt_name = wfd.cFileName;
		ifstream ifs(str_ppt_name, ifstream::binary);
		//读取文件夹中PPS或者PPSX文件
		ifs.seekg(0, ifs.end);
		int length = ifs.tellg();
		ifs.seekg(0);

		char *buffer = new char[length];
		void *p_dec_buf;
		//读取PPS或者PPSX文件的内容
		ifs.read(buffer, length);
		ifs.close();
		//获取密码
		ifs.open(PIN_FILE, ifstream::in);
		if (!ifs)
		{
			MessageBox(NULL, "没有找到密码文件！", "错误", MB_OK);
			return 0;
		}
		else
		{
			ifs.seekg(0, ifs.end);
			int length = ifs.tellg();
			ifs.seekg(0, ifs.beg);

			BYTE *pin = new BYTE[PIN_LEN];
			ifs.read((char *)pin, PIN_LEN);
			ifs.close();

			CAES aes(pin);
			//使用pin对文件夹下的PPS或者PPSX文件进行加密,只加密前128字节
			char p_decrypt_buf[ENCRYPT_LEN] = { 0 };
			memcpy(p_decrypt_buf, buffer, ENCRYPT_LEN);
			aes.Decrypt(reinterpret_cast<void*>(p_decrypt_buf), ENCRYPT_LEN);
			memcpy(buffer, p_decrypt_buf, ENCRYPT_LEN);
		}
		//使用AES解密
		_mkdir(OUTPUT_DIR);
		string new_ppt_name = OUTPUT_DIR + string("\\") + str_ppt_name;
		ofstream ofs(new_ppt_name, ofstream::binary);
		if (ofs)
		{
			ofs.write(buffer, length);
			ofs.close();
			Sleep(2000);
		}
		ShellExecute(NULL, "open", new_ppt_name.c_str(), NULL, NULL, SW_NORMAL);
		Sleep(1000);
		FindClose(handle);
		delete[] buffer;
		while (true)
		{
			//等待POWERPOINT.exe进程关闭
			if (!FindProcess())
			{
				//尝试删除temp文件夹下的PPS或者PPSX文件
				while (remove(new_ppt_name.c_str()) != 0)
				{
					Sleep(500);
				}
				break;
			}
		}
	}
	return 0;
}